<template>
  <div id="show-chat" class="show-chats scroll" @scroll="newPage" ref="showChat">
    <!-- 有消息 -->
    <div v-for="(chat, index) in currentChats" :key="index" class="chat-item">
      <!-- 时间 -->
      <div class="chat-time" v-text="$options.filters.timeFilter(chat.CreateTime)"></div>
      <!-- 内容 -->
      <div class="chat-content" :class="{ 'chat-content-send': chat.IsSend ? true : false }">
        <!-- 头像 -->
        <el-avatar v-if="notShow.indexOf(chat.ContentType) === -1" shape="square" :size="40" :src="getAvatar(chat)"
          title="头像" @click.native="showMemberDetail(chat)">
          <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
        </el-avatar>

        <!-- 群成员id -->
        <div v-if="currentFriendId.indexOf('chatroom') > 0 && !chat.IsSend && notShow.indexOf(chat.ContentType) === -1"
          class="member-info">
          <span v-text="getMemberName(chat.Content)"></span>
          <el-button style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini"
            @click="atSomebody(chat)">
            @Ta
          </el-button>
          <el-button v-if="currentFriend.Owner && currentFriend.Owner === currentWeChatId"
            style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini" :disabled="knicking"
            :loading="knicking" @click="knickSomeBody(chat)">
            踢人
          </el-button>
        </div>

        <!-- content -->
        <div class="content-content" :class="[
          {
            'triangle-send': chat.IsSend && notShow.indexOf(chat.ContentType) === -1
          },
          {
            triangle: notShow.indexOf(chat.ContentType) === -1 && !chat.IsSend
          },
          {
            'chat-room':
              currentFriendId.indexOf('chatroom') > 0 && !chat.IsSend && notShow.indexOf(chat.ContentType) === -1
          },
          { 'system-info': notShow.indexOf(chat.ContentType) > -1 }
        ]">
          <!-- @contextmenu.prevent="rightEvent($event, chat)" -->
          <div class="chat-text" :class="[
            {
              'chat-picture': chat.ContentType === 'Picture' || chat.ContentType === 2
            },
            {
              'chat-voice': chat.ContentType === 'Voice' || chat.ContentType === 3
            },
            {
              'chat-video': chat.ContentType === 'Video' || chat.ContentType === 4
            },
            {
              'chat-link': chat.ContentType === 'Link' || chat.ContentType === 6
            },
            {
              'chat-file': chat.ContentType === 'File' || chat.ContentType === 8
            },
            {
              'chat-namecard': chat.ContentType === 'NameCard' || chat.ContentType === 9
            },
            {
              'chat-luckmoney': chat.ContentType === 'LuckyMoney' || chat.ContentType === 11
            },
            {
              'chat-moneytran': chat.ContentType === 'MoneyTrans' || chat.ContentType === 12
            },
            {
              'chat-app': chat.ContentType === 'WeApp' || chat.ContentType === 13
            },
            { 'chat-system': notShow.indexOf(chat.ContentType) > -1 }
          ]" @click="whatToDo(chat)" v-html="decodeChat(chat)"></div>
        </div>

        <!-- 发送结果 -->
        <div class="send-state" :class="{
          'chat-room':
            currentFriendId.indexOf('chatroom') > 0 && !chat.IsSend && notShow.indexOf(chat.ContentType) === -1
        }">
          <!-- 发送状态 -->
          <el-button v-if="chat.IsSend && !chat.MsgSvrId && !chat.Status && notShow.indexOf(chat.ContentType) === -1"
            type="text" class="el-icon-loading"></el-button>

          <!-- 消息撤回 -->
          <el-button v-if="chat.IsSend && chat.MsgSvrId && revokeMap.indexOf(chat.ContentType) >= 0"
            style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini"
            @click="revokeMessageTask(chat)">
            撤回
          </el-button>

          <!-- 转发 -->
          <el-button v-if="chat.MsgSvrId && transportType.indexOf(chat.ContentType) >= 0"
            style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini" class="el-icon-s-promotion"
            @click="canTransform(chat)">
            转发
          </el-button>

          <!-- 引用 -->
          <el-button v-if="chat.MsgSvrId && quoteType.indexOf(chat.ContentType) >= 0"
            style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini" class="el-icon-s-promotion"
            @click="quoteMsg(chat)">
            引用
          </el-button>

          <!-- 收藏 -->
          <el-button v-if="chat.MsgSvrId && collectionType.indexOf(chat.ContentType) >= 0"
            style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini" class="el-icon-s-promotion"
            title="收藏之后可以发送好友" @click="collectionMsg(chat)">
            收藏
          </el-button>

          <div>
            <div>
              <el-button v-if="chat.MsgSvrId && collectionType.indexOf(chat.ContentType) >= 0"
                style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini" class="el-icon-picture"
                title="保存朋友圈截图" @click="setJietuContent(chat, 0)">
                朋友圈截图
              </el-button>
            </div>
            <div style="margin-top: 5px;">
              <el-button v-if="chat.MsgSvrId && collectionType.indexOf(chat.ContentType) >= 0"
                style="margin-left: 10px; color: #909399; padding: 5px" type="plant" size="mini"
                class="el-icon-picture-outline" title="保存群聊截图" @click="setJietuContent(chat, 1)">
                群聊截图
              </el-button>
            </div>
          </div>
          <!-- 快速发朋友圈 -->
          <el-checkbox v-if="chat.MsgSvrId && (chat.ContentType === 'Picture' || chat.ContentType === 'Text')"
            :checked="chatListMap.indexOf(chat.MsgSvrId) >= 0" style="margin-left: 10px; color: #909399; padding: 5px"
            @change="setCircleContent(chat)">
            选为待发素材
          </el-checkbox>

          <!-- 手机截屏 -->
          <svg class="icon" style="font-size: 20px; cursor: pointer" aria-hidden="true" @click="screenCapture(chat)">
            <use xlink:href="#iconjianqie"></use>
          </svg>
        </div>
      </div>
    </div>

    <!-- 大图 -->
    <!-- <div id="bigImage" class="demo-image__preview big-img-box"> -->
    <div class="demo-image__preview big-img-box">
      <el-image id="bigImageBox" style="width: 100px; height: 100px" :src="bigImageUrl"
        :preview-src-list="[bigImageUrl]"></el-image>
    </div>

    <!-- 群成员详情 -->
    <el-dialog class="member-detail" title="群成员详情" :modal="false" :visible.sync="memberDialog">
      <div class="member-detail-info">
        <el-avatar shape="square" :size="100" :src="memberDetail.Avatar">
          <i class="fa fa-picture-o" aria-hidden="true" title="头像miss"></i>
        </el-avatar>
        <div class="member-detail-text">
          <p>
            微信：
            <span v-text="memberDetail.FriendId"></span>
          </p>
          <p>
            昵称：
            <span v-text="memberDetail.FriendNick || '- -'"></span>
          </p>
          <p>
            性别：
            <span v-text="memberDetail.Gender || '- -'"></span>
          </p>
          <p>
            地址：
            <span v-text="memberDetail.Province || '-'"></span>
            &nbsp;
            <span v-text="memberDetail.City || '-'"></span>
          </p>
        </div>
      </div>
      <div class="member-detail-btns">
        <el-button v-if="!friendsMap[memberDetail.FriendId]"
          style="background-color: #ff9f00; color: #ffffff; border: none" size="medium" @click="getMemberDetail">
          获取详情
        </el-button>
        <el-button v-if="!friendsMap[memberDetail.FriendId]"
          style="background-color: #ff9f00; color: #ffffff; border: none" size="medium" @click="addToAddress">
          添加到通讯录
        </el-button>
      </div>
    </el-dialog>

    <!-- 红包详情 -->
    <el-dialog class="hb-detail" title="红包详情" append-to-body :visible.sync="hbDetailVisible">
      <ul>
        <li>当前微信：{{ hbDetail.WeChatId }}</li>
        <li>红包来源：{{ hbDetail.HbUrl | hbUrlFilter }}</li>
        <li>红包总数：{{ hbDetail.TotalNum }}</li>
        <li>红包总金额：{{ hbDetail.TotalAmount }}</li>
        <li>已抢的数量：{{ hbDetail.RecNum }}</li>
        <li>已抢的金额：{{ hbDetail.RecAmount }}</li>
      </ul>
      抢红包的好友列表
      <el-table :data="hbDetail.Records || []" style="width: 100%">
        <el-table-column prop="UserName" label="微信id" width="180"></el-table-column>
        <el-table-column prop="UserName" label="微信昵称" width="180" :formatter="userNameFormatter"></el-table-column>
        <el-table-column prop="Amount" label="金额"></el-table-column>
        <el-table-column prop="Time" label="时间" width="200">
          <template slot-scope="scope">
            <span v-text="$options.filters.timeFilter(scope.row.Time)"></span>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer">
        <el-button style="background-color: #fff; border: solid #eeeeee 1px; color: #999999" size="medium"
          @click="hbDetailVisible = false">
          取 消
        </el-button>
        <el-button style="background-color: #ff9f00; border: solid #ff9f00 1px" size="medium" type="primary"
          @click="takeLuckMoney(hb2detail)">
          打 开
        </el-button>
      </span>
    </el-dialog>

    <!-- 转发 -->
    <el-dialog append-to-body class="transport-message" title="转发消息" :visible.sync="transportMessageVisible"
      :close-on-click-modal="false" :before-close="beforeCloseHandle">
      <el-tabs v-model="activeName">
        <!-- 好友 -->
        <el-tab-pane label="转发好友" name="friends">
          <div class="friends-list">
            <el-table ref="multipleTable" :data="friendsPages[currentPage - 1]" stripe border style="width: 100%"
              height="400px" @selection-change="handleSelectionChange">
              <el-table-column label="昵称" prop="FriendNick"></el-table-column>
              <el-table-column label="头像" width="70px">
                <template slot-scope="scope">
                  <el-image style="width: 50px; height: 50px" :src="scope.row.Avatar">
                    <div slot="error" class="image-slot">
                      <i style="font-size: 50px" class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column label="备注名" prop="Memo"></el-table-column>
              <el-table-column type="selection" width="55"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination :current-page="currentPage" :page-sizes="[50, 100, 150, 200]" :page-size="pageSize"
              :pager-count="7" layout="total, sizes, prev, pager, next, jumper" :total="totalFriendNum"
              @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
          </div>
        </el-tab-pane>
        <!-- 群聊 -->
        <el-tab-pane label="转发群聊" name="chatrooms">
          <div class="friends-list">
            <el-table ref="multipleTable2" :data="chatRoomsPages[currentPage - 1]" stripe border style="width: 100%"
              height="400px" @selection-change="handleSelectionChange">
              <!-- <el-table-column type="index" :index="indexMethod" label="序号" width="60px"></el-table-column> -->
              <el-table-column label="昵称" prop="NickName"></el-table-column>
              <el-table-column label="头像" width="70px">
                <template slot-scope="scope">
                  <el-image style="width: 50px; height: 50px" :src="scope.row.Avatar">
                    <div slot="error" class="image-slot">
                      <i style="font-size: 50px" class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column label="备注名" prop="Memo"></el-table-column>
              <el-table-column type="selection" width="55"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination :current-page="pageNo" :page-sizes="[50, 100, 150, 200]" :page-size="chatRoomPageSize"
              :pager-count="7" layout="total, sizes, prev, pager, next, jumper" :total="totalChatRoomNum"
              @size-change="handleChatRoomSizeChange" @current-change="handleChatRoomCurrentChange"></el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer">
        <el-button size="small" @click="transportMessageVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="forwardMessage">转发消息</el-button>
      </div>
    </el-dialog>
    <el-dialog title="转发截图保存" append-to-body :visible.sync="screenshotVisible" width="650px">
      <div style="line-height: 50px; font-size: 20px;">
        {{ screen.type==0 ? '朋友圈截图': '群聊截图' }} 
      </div>
      <div style="display: flex; justify-self:row">
        <div v-for="item in screen.imgs" style="width: 300px;margin-right: 10px;">
          <img :src="item"  style="width: 300px;"/>
        </div>
      </div>
      <div style="width: 100%;display: flex;flex-direction: row-reverse;">
        <el-button @click="saveScreen">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapState } from 'vuex'

import phiz from '@/utils/phiz.js'
import { addResources } from '@/api/httpApi'
import {
  TriggerHistoryMsgPushTask,
  RequestTalkDetailTask,
  RevokeMessageTask,
  PullEmojiInfoTask,
  ScreenShotTask,
  RequestContactsInfoTask
} from '@/api/webSocketApi'
import html2canvas from 'html2canvas';
import { fileUpload } from '@/utils/upload'
import { forwardSave } from '@/api/admin/custom'

const imgError = require('assets/svg/conversation-image-error.svg')
const transferMoney = require('assets/svg/conversation-transfer-money.svg')

export default {
  data() {
    return {
      size: 10,
      notShow: ['System', 'Sys_LuckyMoney', 'RoomSystem', 'PaiYiPai', 5, 16, 17, 26], // 符合条件的将不显示头像
      revokeMap: ['Text', 'NameCard', 'Picture', 'Voice', 'Video', 'File', 'Link', 'WeApp', 'Emoji', 'QuoteMsg'], // 符合的才显示撤回按钮
      detailDialogVisible: false, // 显示大图
      knicking: false, // 正在踢人
      memberDialog: false, // 正在撤回消息
      memberDetail: {}, // 群成员详情
      hb2detail: {}, // 群成员详情
      bigImageUrl: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png', // 大图的地址

      transportMessageVisible: false, // 显示转发
      activeName: 'friends', // 转发的默认tab
      currentPage: 1, // 当前页
      pageSize: 50, // 每页消息数
      pageNo: 1, // 当前页
      chatRoomPageSize: 50, // 每页消息数
      chat2Transport: {}, // 要转发的消息
      multipleSelection: [], // 要发送的对象
      transportType: [1, 2, 4, 6, 8, 13, 'Text', 'Picture', 'Video', 'Link', 'WeApp', 'File'], // 能转发的消息类型
      quoteType: [1, 2, 4, 'Text', 'Picture', 'Video'], // 能引用的消息类型
      collectionType: [6, 13, 14, 'Link', 'WeApp', 'Emoji', 'Picture'], // 能收藏的消息类型
      // showRight: false, // 显示右键菜单
      chatChose: {}, // 右键选择的聊天
      lastScrollTop: 0, //
      lastFetchTime: 0, // 最后的请求时间,
      screenshotVisible: false,
      screen: {}
    }
  },
  computed: {
    ...mapState('nedb', {
      friends: 'friends', // 通讯录列表
      chatRooms: 'chatRooms', // 当前的群聊列表
      strangers: 'strangers', // 陌生人列表
      currentMode: 'currentMode' // web还是pc
    }),
    ...mapGetters({
      currentUser: 'currentUser',

      friendsPages: 'nedb/friendsPages', // 通讯录数据 分页
      luckMoneyMap: 'nedb/luckMoneyMap',
      chatRoomsPages: 'nedb/chatRoomsPages', // 当前的群聊列表 分页
      friendsMap: 'nedb/friendsMap',
      strangersMap: 'nedb/strangersMap',

      hbDetail: 'conversation/hbDetail',
      atContent: 'conversation/content',
      currentChats: 'conversation/currentChats', // 当前好友的聊天记录
      currentWechat: 'conversation/currentWechat',
      currentFriend: 'conversation/currentFriend',
      currentFriendId: 'conversation/currentFriendId',
      currentWeChatId: 'conversation/currentWeChatId',
      bigImageMap: 'conversation/bigImageMap',

      chatListMap: 'circleManager/chatListMap'
    }),
    // 总的好友数
    totalFriendNum() {
      return this.friends.length
    },
    // 总的群聊数
    totalChatRoomNum() {
      return this.chatRooms.length
    },
    chatslength() {
      return this.currentChats.length
    },
    // 显示红包详情
    hbDetailVisible: {
      get() {
        return this.$store.getters['conversation/hbDetailVisible']
      },
      set(v) {
        this.$store.commit('conversation/SET_HB_DETAIL_VISIBLE', v)
        if (!v) {
          this.$store.commit('conversation/SET_HB_DETAIL', {
            WeChatId: '', // 所属微信号
            Success: false,
            ErrMsg: '',
            HbUrl: '', //
            TotalNum: null, // 红包总个数
            TotalAmount: null, // 红包总金额
            RecNum: null, // 已收红包个数
            Records: [], // 已收红包个数
            RecAmount: null // 已收红包金额
          })
          this.hb2detail = {}
        }
      }
    }
  },
  watch: {
    // 微信id
    currentWeChatId(val) {
      // 重置数据
      this.lastFetchTime = 0
      this.$store.commit('conversation/RESET_CURRENT_CHATS')
      if (val && this.currentFriendId) {
        TriggerHistoryMsgPushTask(val, this.currentFriendId, 0, 0, 10)
      }
    },
    // 好友id
    currentFriendId(val) {
      // 重置数据
      this.lastFetchTime = 0
      this.$store.commit('conversation/RESET_CURRENT_CHATS')
      if (val && this.currentWeChatId) {
        TriggerHistoryMsgPushTask(this.currentWeChatId, val, 0, 0, 10)
      }
    },
    // 聊天长度变化
    chatslength(newLength, oldLength) {
      // 切换好友 置底
      if (oldLength === 0 && newLength > 0) {
        this.$nextTick(function () {
          if (newLength > oldLength) {
            setTimeout(() => {
              this.setBottom()
            }, 200)
          }
        })
      }
      // 收到新消息置底
      if (newLength - oldLength === 1 && this.lastScrollTop >= 20) {
        setTimeout(() => {
          this.setBottom()
        }, 100)
      }
    }
  },
  methods: {
    async captureScreenshot() {
      try {
        // 显示加载状态
        const target = document.getElementsByClassName("conversation-chats")[0];

        // 1. 保存原始状态（避免影响页面样式）
        const originalStyle = {
          width: target.style.width,
          height: target.style.height,
          overflow: target.style.overflow,
        };

        // 2. 强制展开滚动区域：设置宽高为内容完整尺寸
        target.style.width = `${target.scrollWidth}px`;
        target.style.height = `${target.scrollHeight}px`;
        target.style.overflow = 'visible'; // 让滚动内容全部显示

        // 3. 滚动到顶部（确保从最开始截图）
        target.scrollTop = 0;
        target.scrollLeft = 0;


        // 使用html2canvas捕获DOM元素
        const canvas = await html2canvas(target, {
          width: target.scrollWidth,  // 强制匹配内容宽度
          height: target.scrollHeight, // 强制匹配内容高度
          scrollX: 0, // 从最左开始
          scrollY: 0, // 从最上开始
          useCORS: true,       // 允许跨域图片
          logging: false       // 关闭日志
        });

        // 截图完成后恢复滚动位置
        // 5. 恢复原始样式（避免影响页面）
        Object.assign(target.style, originalStyle);

        // 将Canvas转换为Blob对象
        const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'));

        // 创建FormData并上传
        const formData = new FormData();
        formData.append('myfile', blob, 'chat_screenshot.png');
        // 调用上传API
        const res = await fileUpload(formData);
        if (res.bizCode === 0 && res.data) {

          return res.data.url;
        } else {
          throw new Error(res.message || '上传失败，服务器返回错误');
        }
        // 可选：自动下载截图
        // this.downloadImage(dataUrl);
      } catch (error) {
        console.error('截图失败:', error);
        alert('截图失败，请重试');
      }
    },
    // 手机截屏
    screenCapture(chat) {
      if (chat.MsgSvrId) {
        ScreenShotTask(this.currentWeChatId, 0, this.currentFriendId, chat.MsgSvrId)
        this.$message.success('截屏任务已下发,请耐心等待!')
      }
    },
    // scroll消息置底
    setBottom() {
      const docSC = document.getElementById('show-chat')
      if (docSC) {
        const sh = document.getElementById('show-chat').scrollHeight
        const ch = document.getElementById('show-chat').clientHeight
        document.getElementById('show-chat').scrollTop = sh - ch
      }
    },
    // 到顶分页加载chats
    newPage() {
      const st = document.getElementById('show-chat').scrollTop
      const sh = document.getElementById('show-chat').scrollHeight
      const ch = document.getElementById('show-chat').clientHeight
      this.lastScrollTop = st
      if (st === 0 && sh > ch) {
        const endTime = this.currentChats[0] ? this.currentChats[0].CreateTime : 0
        if (endTime === this.lastFetchTime) return
        this.lastFetchTime = endTime
        TriggerHistoryMsgPushTask(this.currentWeChatId, this.currentFriendId, 0, endTime, 10)
      }
    },
    // 获取聊天的头像
    getAvatar(chat) {
      // 自己发的消息
      if (chat.IsSend) {
        return this.currentWechat.Avatar || ''
      } else if (chat.FriendId && chat.FriendId.indexOf('chatroom') > 0) {
        //   群消息
        const memberId = chat.Content.split(':')[0]
        if (this.friendsMap[memberId]) {
          return this.friendsMap[memberId].Avatar
        } else if (this.strangersMap[memberId]) {
          return this.strangersMap[memberId].Avatar
        } else {
          return ''
        }
      } else {
        // 好友的消息
        return this.currentFriend.Avatar
      }
    },
    // 抢红包的昵称
    userNameFormatter(row) {
      const wxid = row.UserName
      if (this.friendsMap[wxid]) {
        return this.friendsMap[wxid].FriendNick
      } else if (this.strangersMap[wxid]) {
        return this.strangersMap[wxid].FriendNick
      } else {
        return '本地数据库没有该好友的信息'
      }
    },
    // 获取群聊发言人的昵称
    getMemberName(content) {
      const memberId = content.split(':')[0]
      let name = memberId
      if (this.friendsMap[memberId]) {
        name = this.friendsMap[memberId].FriendNick
      } else if (this.strangersMap[memberId]) {
        name = this.strangersMap[memberId].Nickname
      }
      return name
    },
    // 获取群成员详情
    showMemberDetail(chat) {
      if (this.currentFriendId.indexOf('chatroom') < 0) {
        // 不是群就返回
        return
      }
      if (this.currentFriendId) {
        const member = chat.Content.split(':')[0]
        if (this.friendsMap[member]) {
          this.memberDetail = this.friendsMap[member]
          this.memberDialog = true
        } else if (this.strangersMap[member]) {
          this.memberDetail = {
            WeChatId: this.currentWeChatId,
            FriendId: member,
            Avatar: this.strangersMap[member].Avatar ? this.strangersMap[member].Avatar : '',
            FriendNick: this.strangersMap[member].Nickname ? this.strangersMap[member].Nickname : '',
            LabelIds: ''
          }
          this.memberDialog = true
        } else {
          this.memberDetail = {
            WeChatId: this.currentWeChatId,
            FriendId: member,
            Avatar: '',
            FriendNick: '',
            LabelIds: ''
          }
          this.getMemberDetail()
        }
      }
    },
    // 添加到通讯录
    addToAddress() {
      const content = {
        WeChatId: this.memberDetail.WeChatId, // 商家个人微信内部全局唯一识别码
        ChatroomId: this.currentFriendId, // 所在的群聊id
        FriendId: this.memberDetail.FriendId, // 请求加好友微信内部全局唯一识别码
        Message: '', // 招呼语
        Remark: '' // 备注信息
      }
      this.$store.dispatch('websocket/AddFriendInChatRoomTask', content)
      this.memberDialog = false
      this.$message.info('指令已经下发！')
    },
    // 获取详情
    getMemberDetail() {
      RequestContactsInfoTask(this.memberDetail.WeChatId, this.memberDetail.FriendId)
      this.memberDialog = false
      this.$message.info('指令已经下发！')
    },
    // base64解码 & 不同类型的消息解读
    decodeChat(chat) {
      try {
        let content = chat.Content
        const regJson = new RegExp(/^{.+}$/)
        let jContent = {}
        let thumb = ''
        let str = ''
        let nickName = ''
        if (chat.FriendId && chat.FriendId.indexOf('chatroom') > 0 && !regJson.test(content)) {
          if (!content.startsWith('http')) {
            content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
          }
        }
        if (typeof content === 'string' && regJson.test(content)) {
          jContent = JSON.parse(content)
        }
        switch (chat.ContentType) {
          // 文本 1
          case 'Text':
          case 1:
            return phiz.qqFaceImgMap(content)
          // 图片 2
          case 'Picture':
          case 2:
            if (jContent.Thumb && jContent.Thumb.startsWith('http')) {
              return `<img class="chat-img" src="${jContent.Thumb}" title="点击看大图" alt="图片"/>`
            } else if (chat.Url) {
              return `<img class="chat-img" src="${chat.Url}" title="点击看大图" alt="图片"/>`
            } else if (jContent.Thumb || jContent.Thumb === '') {
              return `<img class="chat-img" src="${imgError}" title="点击看大图" alt="图片"/>`
            } else {
              return `<img class="chat-img" src="${content}" title="点击看大图" alt="图片"/>`
            }
          // 语音 3
          case 'Voice':
          case 3:
            if (chat.Url || this.bigImageMap[chat.MsgId]) {
              return ` <audio src="${chat.Url || this.bigImageMap[chat.MsgId]}" alt="语音" controls></audio>`
            } else if (content.endsWith('.amr')) {
              thumb = content.replace(/.amr$/, '.mp3')
            } else {
              thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
            }
            if (thumb.startsWith('http://')) {
              return ` <audio src="${thumb}" alt="语音" controls></audio>`
            } else {
              // return ` <p>[语音]文件地址错误，点击重新获取</p>`
              return chat
            }
          // 视频 4
          case 'Video':
          case 4:
            if (chat.Url || this.bigImageMap[chat.MsgId]) {
              str = `<video class="video-box" src="${chat.Url || this.bigImageMap[chat.MsgId]
                }" type="video/mp4" alt="视频" controls></video>`
            } else if (jContent.Thumb && jContent.Thumb.startsWith('http')) {
              str = `<img class="video-box-no" src="${jContent.Thumb}"  alt="视频" />
                 <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击播放"></i>`
            } else if (jContent.Thumb || jContent.Thumb === '') {
              str = `<img class="video-box-no" src="${imgError}"  alt="视频" />
                 <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击播放"></i>`
            } else {
              str = `<video class="video-box" src="${content}" type="video/mp4" alt="视频"></video>`
            }
            return str
          // 系统消息 5 ok
          case 'System':
          case 5:
            return content
          // 链接消息 6
          case 'Link':
          case 6:
            if (typeof content === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
              switch (jContent.TypeStr) {
                case '[聊天记录]':
                  str = `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                         <span class="link-des">${jContent.Des}...</span>
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
                  break
                default:
                  // 其他类型 笔记 音乐 视频 小视频 表情分享 游戏录频
                  str = `
                        <span class="link-title">${jContent.Title}</span>
                        <div class="link-content">
                         <span class="link-des">${jContent.Des}</span>
                          <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                        </div>
                        <div class="link-type">${jContent.TypeStr}</div>
                        `
                  break
              }
              return str
            } else {
              return content
            }
          // 扩展的链接消息（小程序分享等），内容为xml格式，暂未使用 7
          case 'LinkExt':
          case 7:
            return `LinkExt消息：${content}`
          // 文件 8
          case 'File':
          case 8:
            if (JSON.stringify(jContent) !== '{}') {
              let size = 0
              let type = ''
              if (jContent.size) {
                if (jContent.size < 1024) {
                  size = jContent.size + 'B'
                } else if (jContent.size < 1024 * 1024) {
                  size = parseInt(jContent.size / 1024, 10) + 'KB'
                } else {
                  size = parseInt(jContent.size / (1024 * 1024), 10) + 'MB'
                }
              }
              if (jContent.Des) {
                size = jContent.Des.replace(/,.*/, '')
                type = jContent.Des.replace(/.*,/, '').trim()
              }
              const fileSize = size || ''
              const fileTitle = jContent.Title || jContent.name || ''
              const fileType = type || jContent.name || ''
              const fileSource = jContent.Source || '手机'
              let fileIcon = 'fa-question-circle-o'

              switch (fileType) {
                case 'doc':
                case 'docx':
                  fileIcon = 'fa-file-word-o'
                  break
                case 'xls':
                case 'xlsx':
                  fileIcon = 'fa-file-excel-o'
                  break
                case 'ppt':
                case 'pptx':
                  fileIcon = 'fa-file-powerpoint-o'
                  break
                case 'zip':
                case 'rar':
                  fileIcon = 'fa-file-archive-o'
                  break
                case 'text':
                case 'txt':
                  fileIcon = 'fa-file-text-o'
                  break
                case 'mp3':
                  fileIcon = 'fa-file-sound-o'
                  break
                default:
                  fileIcon = 'fa-question-circle-o'
                  break
              }
              str = `
                  <span class="file-title">${fileTitle}</span>
                  <div class="file-content">
                    <span class="file-des">${fileSize}</span>
                    <i class="fa ${fileIcon} file-icon" aria-hidden="true"></i>
                  </div>
                  <div class="file-type">${fileSource}</div>
                `
              return str
            } else {
              return content
            }
          // 名片 9
          case 'NameCard':
          case 9:
            if (jContent.Nickname) {
              thumb = jContent.HeadImg ? jContent.HeadImg : ''
              nickName = jContent.Nickname
            } else {
              thumb = this.friendsMap[content] ? this.friendsMap[content].Avatar : ''
              nickName = this.friendsMap[content] ? this.friendsMap[content].FriendNick : ''
            }
            str = `
                    <div class="namecard-info">
                      <img class="namecard-img" src="${thumb}" alt="好友头像" />
                      <span class="namecard-nickname ellipsis2">${nickName}</span>
                    </div>
                    <div class="namecard-tip">个人名片</div>
                  `
            return str
          // 位置信息 10
          case 'Location':
          case 10:
            return `位置消息：${content}`
          // 红包 11
          case 'LuckyMoney':
          case 11:
            {
              let wish = '恭喜发财，大吉大利'
              if (jContent.Title) {
                wish = jContent.Title
              }
              const flag = this.luckMoneyMap[chat.MsgSvrId] ? '已领取' : ''
              str = `
                  <div class="luck-info">
                    <span class="luck-img" > &nbsp;&nbsp;🧧 </span>
                    <span class="luck-wish ellipsis2" >${wish}</span>
                    <span class="luck-flag ellipsis2" >${flag}</span>
                  </div>
                  <div class="luckmoney-tip">微信红包</div>
                  `
            }
            return str
          // 转账 12
          case 'MoneyTrans':
          case 12: {
            let moneyTransFlag = ''

            switch (jContent.PaySubType) {
              case 1:
                if (chat.IsSend) {
                  moneyTransFlag = `转账给${this.currentFriend.FriendNick}`
                } else {
                  moneyTransFlag = '转账给你'
                }
                break
              case 3:
                moneyTransFlag = '已收钱'
                break
              default:
                break
            }
            if (jContent.PaySubType === 3) {
              str = `
                        <div class="moneytran-info">
                            <img class="moneytran-img" src="${transferMoney}" alt />
                            <span class="moneytran-feed" >${jContent.Feedesc || 0}</span>
                            <span class="moneytran-flag">${moneyTransFlag}</span>
                            <span class="moneytran-flag"></span>
                        </div>
                        <div class="moneytran-tip">微信转账</div>
                    `
            } else {
              const flag = this.luckMoneyMap[chat.MsgSvrId] ? '已被领取' : ''
              str = `
                        <div class="moneytran-info">
                            <img class="moneytran-img" src="${transferMoney}" alt />
                            <span class="moneytran-feed" >${jContent.Feedesc || 0}</span>
                            <span class="moneytran-flag">${moneyTransFlag}</span>
                            <span class="moneytran-flag">${flag}</span>
                        </div>
                        <div class="moneytran-tip">微信转账</div>
                  `
            }
            return str
          }
          // 小程序 13
          case 'WeApp':
          case 13: {
            let appIcon = imgError
            let appSource = '无效小程序'
            let appTitle = '无效小程序'
            let appThumb = ''
            let appTypeStr = '小程序'
            if (typeof content === 'string' && regJson.test(content)) {
              jContent = JSON.parse(content)
              appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
              appSource = jContent.Source
              appTitle = jContent.Title || jContent.Des
              appThumb = jContent.Thumb
              appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
            }

            str = `
                  <div class="app-des">
                  <img class="app-icon" src="${appIcon}" alt="icon" />
                  <span class="app-source ellipsis">${appSource}</span>
                  </div>
                  <div class="app-title ellipsis">${appTitle}</div>
                  <img class="app-img" src="${appThumb}" />
                  <div class="app-typestr">${appTypeStr}</div>
                   `
            return str
          }
          // Emoji 14
          case 'Emoji':
          case 14: {
            const eMap = {
              'jsb_j.png': 'http://emoji.qpic.cn/wx_emoji/abG5b87mcOW7YxBZFZPZOBXUjE99n48g6Znn6zaUiaVRtxMBYaEEKoA/',
              'jsb_s.png': 'http://emoji.qpic.cn/wx_emoji/ARQOAfC52Cu6iczyCvLhibUNQxCialTeaeObDoEMsL7uJjyV5dqzCNCFQ/',
              'jsb_b.png': 'http://emoji.qpic.cn/wx_emoji/Ty7jp6YeVib7MibicS8eb9buorVCg7mYTFXxuEpVDyQMaqK6PUoOcGxbQ/',
              'dice_1.png': 'http://emoji.qpic.cn/wx_emoji/QsDXJwBwXEXGFwLHJCm6haBlFls30vzPQcZTib9dyhLiazKxoPX6kp0A/',
              'dice_2.png':
                'http://emoji.qpic.cn/wx_emoji/YbCHM38dRYCIWbKmiaBrdnPrfuuwicLD2iacSWaPoAiaFrUySG87ELibOXQ/',
              'dice_3.png': 'http://emoji.qpic.cn/wx_emoji/lgVbvPFtzP8ytMiaKZMUoV3BXNPRfUaP69vozHfNarmX3MlTrgOhrkA/',
              'dice_4.png': 'http://emoji.qpic.cn/wx_emoji/zaBCJf5hVDn8NlibdrxV4NoPc12d28S7s67UCJqwynRmB0spdttIbeQ/',
              'dice_5.png': 'http://emoji.qpic.cn/wx_emoji/72IJJTdBzuibcxvnpFVicUAzCWRJC3cKhtkpMHTFejC2cyOeEGSHibTKw/',
              'dice_6.png': 'http://emoji.qpic.cn/wx_emoji/Jowow1icuI3XqtkFeQgIuzjIEYHdtJZictGFJjTsAFwW1g6cx1uTaQfw/'
            }
            thumb = jContent.Thumb || jContent.cdnUrl
            if (thumb) {
              if (eMap[thumb]) {
                return `<img class="chat-img" src="${eMap[thumb]}" title="点击看大图" alt="图片"/>`
              }
              return `<img class="chat-img" src="${thumb}" title="点击看大图" alt="图片"/>`
            }
            return content
          }
          // 群管理消息 15
          case 'RoomManage':
          case 15:
            //   return content
            return 'RoomManage'
          // 红包系统消息 16
          case 'Sys_LuckyMoney':
          case 16:
            return JSON.parse(chat.Content).Title
          // 群系统消息 17 ok
          case 'RoomSystem':
          case 17:
            if (jContent.title) {
              return jContent.title
            }
            return content
          case 'NotifyMsg':
          case 21:
            if (jContent.title) {
              return `
                      <span class="link-title">${jContent.source}</span>
                      <div class="link-content">
                       <span class="link-des">${jContent.title}...</span>
                      </div>
                      <div class="link-type">${jContent.des}</div>
                      `
            }
            return content
          case 'BizLink':
            return content
          // 引用消息
          case 22:
          case 'QuoteMsg':
            if (jContent.title) {
              if (jContent.displayName) {
                str =
                  phiz.qqFaceImgMap(jContent.title) +
                  `<div class="quote-content"><span class="link-des">${jContent.displayName}:${jContent.content}</span></div>`
                return str
              } else {
                return jContent
              }
            }
            return '引用消息' + content
          // 视屏号
          case 24:
          case 'ShiPinHao':
            if (jContent.title) {
              return `
                    <div>
                      <p>${jContent.title}</p>
                      <img style="width:200px;" src="${jContent.thumb}" alt="好友头像" />
                    </div>
                    <div style="display:flex;align-items:center;">
                      <img style="width:30px;border-radius:15px;" class="namecard-img" src="${jContent.avatar}" alt="好友头像" />
                      <span style="margin-left:10px;">${jContent.nickname}</span>
                    </div>
                  `
            }
            return content
          // 拍一拍
          case 26:
          case 'PaiYiPai':
            return content
          // 不支持的消息
          default:
            return `不支持的消息类型 ${chat.ContentType}`
        }
      } catch (error) {
        return chat
      }
    },
    // 点击事件
    whatToDo(chat) {
      switch (chat.ContentType) {
        case 'Voice':
        case 'Picture':
        case 'Video':
        case 'File':
          this.getChatDetail(chat)
          break
        case 'Link':
        case 6:
          this.openLink(chat)
          break
        case 'LuckyMoney':
          this.queryHbDetailTask(chat)
          break
        case 'MoneyTrans':
          this.taskTransMoney(chat)
          break
        default:
          console.log(chat)
          break
      }
    },
    // 获取聊天中各种资源的地址
    getChatDetail(chat) {
      const { WeChatId, FriendId, MsgId, MsgSvrId, ContentType, Url } = chat
      // 先看content中有没有url
      const detailUrl = Url || this.bigImageMap[MsgId] || ''
      if (detailUrl) {
        if (ContentType === 'Picture') {
          // 展示大图
          this.bigImageUrl = detailUrl
          const imgDom = document.getElementById('bigImageBox')
          if (imgDom) {
            imgDom.click()
          }
        } else if (ContentType === 'File') {
          this.$confirm('下载该文件?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              // 下载文件 方法1
              // window.location.href = url
              // 下载文件 方法2
              const a = document.createElement('a')
              a.setAttribute('href', detailUrl)
              a.setAttribute('target', '_blank')
              a.setAttribute('id', 'file_a')
              // 防止反复添加
              if (document.getElementById('file_a')) {
                document.body.removeChild(document.getElementById('file_a'))
              }
              document.body.appendChild(a)
              a.click()
            })
            .catch(() => { })
        } else if (ContentType === 'Video') {
          return
        } else if (ContentType === 'Voice') {
          return
        }
      } else {
        if (MsgSvrId) {
          RequestTalkDetailTask(WeChatId, FriendId, MsgId, MsgSvrId, '', false)
          this.$message({
            type: 'info',
            message: '正在从手机获取资源，请稍后再试！',
            duration: 1000
          })
        } else {
          this.$message({
            type: 'warning',
            message: '没有MsgSvrId不能获取资源！',
            duration: 2000
          })
        }
      }
    },
    // 打开链接
    openLink(chat) {
      let content = chat.Content
      const regJson = new RegExp(/^{.+}$/)
      if (chat.FriendId.indexOf('@chatroom') > 0 || chat.FriendId.indexOf('@im.chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
      }
      if (typeof content === 'string' && regJson.test(content)) {
        const jContent = JSON.parse(content)
        switch (jContent.TypeStr) {
          case '[链接]':
            if (jContent.Title === '邀请你加入群聊' || jContent.Title === '邀请您加入群聊') {
              const contentMsg = {
                WeChatId: chat.WeChatId, // 商家个人微信内部全局唯一识别码
                Talker: chat.FriendId, // 邀请者
                MsgSvrId: chat.MsgSvrId, // 邀请消息的msgSvrId
                MsgContent: JSON.stringify(jContent) // 回传邀请信息的内容（json）
              }
              // 同意加入群聊
              this.$store.dispatch('websocket/AgreeJoinChatRoomTask', contentMsg)
            } else {
              const url = jContent.Url
              if (this.currentMode === 'electron') {
                const { shell } = window.require('electron')
                shell.openExternal(url)
              } else {
                const a = document.createElement('a')
                a.setAttribute('href', url)
                a.setAttribute('target', '_blank')
                a.setAttribute('id', 'js_a')
                // 防止反复添加
                if (document.getElementById('js_a')) {
                  document.body.removeChild(document.getElementById('js_a'))
                }
                document.body.appendChild(a)
                a.click()
              }
            }
            break
          case '[聊天记录]':
            break
          default:
            break
        }
      }
    },
    // 收转账
    taskTransMoney(chat) {
      let content = chat.Content
      const regJson = new RegExp(/^{.+}$/)
      if (chat.FriendId.indexOf('@chatroom') > 0 || chat.FriendId.indexOf('@im.chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
      }
      if (typeof content === 'string' && regJson.test(content)) {
        const jContent = JSON.parse(content)
        if (chat.IsSend) return
        if (jContent.PaySubType && jContent.PaySubType === 3) {
          this.$message({
            type: 'info',
            message: '该转账已经接收！',
            duration: 1000
          })
          return
        }
        // 超时不能打开
        const limiTime = parseInt(new Date().getTime() / 1000, 10)
        if (limiTime - jContent.InvalidTime >= 24 * 60 * 60) {
          this.$message({
            type: 'info',
            message: '该转账已经过期！',
            duration: 1000
          })
          return
        }
        // 打开红包
        const msgContent = {
          WeChatId: chat.WeChatId,
          FriendId: chat.FriendId,
          MsgSvrId: chat.MsgSvrId ? chat.MsgSvrId : chat.MsgSvrId,
          MsgKey: jContent.Key
        }
        this.$store.dispatch('websocket/TakeLuckyMoneyTask', msgContent)
      }
    },
    // 查看红包详情
    queryHbDetailTask(chat) {
      this.hb2detail = chat
      let content = chat.Content
      const regJson = new RegExp(/^{.+}$/)
      if (chat.FriendId.indexOf('@chatroom') > 0 || chat.FriendId.indexOf('@im.chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
      }
      if (typeof content === 'string' && regJson.test(content)) {
        content = JSON.parse(content)
      }
      if (!content.Key || !chat.WeChatId) return

      // 获取详情
      this.$store.dispatch('websocket/QueryHbDetailTask', {
        WeChatId: chat.WeChatId,
        HbUrl: content.Key
      })
      this.$message({
        type: 'info',
        message: '正在获取红包详情！',
        duration: 1000
      })
    },
    // 收红包
    takeLuckMoney(chat) {
      let content = chat.Content
      const regJson = new RegExp(/^{.+}$/)

      if (chat.FriendId.indexOf('@chatroom') > 0 || chat.FriendId.indexOf('@im.chatroom') > 0) {
        content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
      }
      if (typeof content === 'string' && regJson.test(content)) {
        const jContent = JSON.parse(content)
        const time = parseInt(new Date().getTime() / 1000, 10)
        if (chat.IsSend) {
          // 如果是收转账的提示 不做处理
          if (jContent.PaySubType && jContent.PaySubType === 3) {
            return
          }
        } else {
          // 判断是否打开过
          // 如果该消息已经打开
          if (this.luckMoneyMap[chat.MsgSvrId]) {
            // 转账本身已经显示状态和金额 就不再弹框展示
            // 这是弹框展示红包的金额
            if (chat.ContentType === 'LuckyMoney') {
              let amount = 0
              amount = '￥：' + this.luckMoneyMap[chat.MsgSvrId].Amount
              this.$alert('金额' + amount + ' 分', '已经打开', {
                confirmButtonText: '确定',
                callback: () => {
                  return true
                }
              })
            }
          } else {
            // 收转账的消息 不做处理
            if (chat.ContentType === 'MoneyTrans' && jContent.PaySubType === 3) return
            // 红包或者转账过期 不再处理
            if (time - content.InvalidTime >= 24 * 60 * 60) {
              this.$message.warning('已过期')
            } else {
              // 打开红包
              const msgContent = {
                WeChatId: chat.WeChatId,
                FriendId: chat.FriendId,
                MsgSvrId: chat.MsgSvrId ? chat.MsgSvrId : chat.MsgSvrId,
                MsgKey: jContent.Key
              }
              this.$store.dispatch('websocket/TakeLuckyMoneyTask', msgContent)
            }
          }
        }
      }
    },
    // 能转发
    canTransform(chat) {
      if (this.transportType.indexOf(chat.ContentType) >= 0) {
        // 能转发
        this.chat2Transport = chat
        this.transportMessageVisible = true
      } else {
        this.$message.info('该消息类型不能转发！')
      }
    },
    // 收藏
    collectionMsg(chat) {
      if (chat.ContentType === 'Emoji') {
        if (chat.IsSend) {
          this.$message.warning('不能收藏自己发的emoji!')
          return
        }
        const { WeChatId, Content } = chat
        if (WeChatId && Content) {
          const { Md5 } = JSON.parse(Content)
          if (!Md5) return
          PullEmojiInfoTask(WeChatId, Md5)
        }
      } else if (chat.ContentType === 'Picture') {
        const { MsgId, Url } = chat
        // 先看content中有没有url
        const detailUrl = Url || this.bigImageMap[MsgId] || ''
        if (detailUrl) {
          // const message = {
          //   restype: 2,
          //   content: detailUrl // 内容
          // }
          addResources(this.currentUser.SupplierId, detailUrl, 100, '屏幕截图')
            .then((res) => {
              if (res.code === 0) {
                this.$message.success('添加到素材库成功！')
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
        } else {
          this.$message.info('请先获取大图!')
        }
      } else {
        const message = {
          restype: chat.ContentType === 'WeApp' ? 13 : 6,
          content: chat.Content // 内容
        }
        addResources(
          this.currentUser.SupplierId,
          JSON.stringify(message),
          chat.ContentType === 'WeApp' ? 4 : 3,
          chat.MsgSvrId
        )
          .then((res) => {
            if (res.code === 0) {
              this.$message.success('添加到素材库成功！')
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      }
    },
    async setJietuContent(chat, type) {
      let content = chat.Content
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (chat.FriendId && chat.FriendId.indexOf('chatroom') > 0 && !regJson.test(content)) {
        if (!content.startsWith('http')) {
          content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
        }
      }
      if (typeof content === 'string' && regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let url='';
      if (this.bigImageMap[chat.MsgId]) {
            // 本地有大图
            url = this.bigImageMap[chat.MsgId]
          } else {
            // 图片需要获取大图
            await this.getChatDetail(chat)
            url = this.bigImageMap[chat.MsgId]
          }
      //截图当前页面div .conversation-chats 
      this.captureScreenshot().then((canvas) => {
        console.log(canvas);
        this.screen = {
          wxid: this.currentWechat.WeChatId,
          wx_name: this.currentWechat.WeChatNick,
          friendid: this.currentFriend.UserName,
          friend_name:  this.currentFriend.NickName,
          msg_id: chat.MsgSvrId,
          type: type,
          img_url: [canvas, url].join(","),
          imgs:[canvas, url]
        }
        this.screenshotVisible = true;
      });
    },
    saveScreen(){
      forwardSave(this.screen).then((res) => {
        if (res.code === 0) {
          this.$message.success('保存成功！')
          this.screenshotVisible = false;
        }
      });
    },
    // 选为待发素材
    setCircleContent(chat) {
      //this.currentFriend的属性都给chat
      chat = { ...this.currentFriend, ...chat }
      const chatId = this.chatListMap.findIndex((x) => {
        return x === chat.MsgSvrId
      })
      if(!chat.FriendNick){
        chat.FriendNick=chat.NickName;
      }
      if(!chat.FriendNick){
        chat.FriendNick=chat.ShowName;
      }
      
      //设置名称
      if (chatId >= 0) {
        this.$store.commit('circleManager/REMOVE_CHAT_LIST', chatId)
      } else {
        this.$store.commit('circleManager/SET_CHAT_LIST', chat)
        if (chat.ContentType === 'Picture') {
          // 判断是否有大图
          if (chat.Url) {
            return
          } else if (this.bigImageMap[chat.MsgId]) {
            // 本地有大图
            chat.Url = this.bigImageMap[chat.MsgId]
          } else {
            // 图片需要获取大图
            this.getChatDetail(chat)
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    beforeCloseHandle(done) {
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection() // 删除后清空之前选择的数据
      this.$refs.multipleTable2.clearSelection() // 删除后清空之前选择的数据
      done()
    },
    // 转发
    forwardMessage() {
      if (this.multipleSelection.length === 0) {
        this.$alert('至少选择一个转发对象！', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      } else if (this.multipleSelection.length > 9) {
        this.$alert('最多只能选择9个转发对象！', '提示', {
          type: 'warning',
          confirmButtonText: '确定'
        })
        return
      } else {
        const friendIds = []
        this.multipleSelection.forEach((x) => {
          if (x.FriendId) {
            friendIds.push(x.FriendId)
          } else {
            friendIds.push(x.UserName)
          }
        })
        const parameter = {
          MsgSrvId: this.chat2Transport.MsgSvrId, // 消息Id
          WeChatId: this.chat2Transport.WeChatId, //
          FriendIds: friendIds.join(','), // 目标人群id列表，用逗号,分隔
          ExtMsg: '', // 附带消息
          Talker: this.chat2Transport.FriendId // 转发消息的会话
        }
        this.$store.dispatch('websocket/ForwardMessageTask', parameter)
        this.transportMessageVisible = false
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection() // 删除后清空之前选择的数据
        this.$refs.multipleTable2.clearSelection() // 删除后清空之前选择的数据
      }
    },
    // 修改pageSize
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 修改pageSize
    handleChatRoomSizeChange(val) {
      this.chatRoomPageSize = val
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleChatRoomCurrentChange(val) {
      this.pageNo = val
    },
    // 消息撤回
    revokeMessageTask(chat) {
      if (new Date().getTime() - chat.CreateTime >= 1000 * 60 * 2) {
        this.$message.warning('消息发出超过2分钟，不能测回！')
        return
      }
      RevokeMessageTask(this.currentWeChatId, this.currentFriendId, chat.MsgSvrId, '')
    },
    // @群成员 该方法只支持@一个人 如果要同时@多人请修改逻辑
    atSomebody(chat) {
      const memberId = chat.Content.split(':')[0]
      const memberName = this.getMemberName(chat.Content)
      // 如果要@的人已经不在群聊
      if (this.currentFriend.MemberList.indexOf(memberId) < 0) {
        this.$message.warning('该成员已经不在群里！')
        return
      }
      this.$store.commit('conversation/SET_REMARK', memberId)
      // 这里的不是空格是\u2005
      this.$store.commit('conversation/SET_CONTENT', `${this.atContent}@${memberName}\u2005`)
    },
    // 引用消息
    quoteMsg(chat) {
      const qc = {
        quoteSvrId: chat.MsgSvrId || chat.MsgSvrId,
        quoteType: chat.ContentType
      }
      // 群聊
      if (chat.FriendId.endsWith('chatroom')) {
        if (chat.IsSend) {
          // 引用自己的消息
          qc.displayName = this.currentWechat.WeChatNick
          qc.quoteUser = this.currentWechat.WeChatId
          qc.content = chat.Content
        } else {
          // 引用群成员的消息
          const chatContent = chat.Content
          const memberId = chatContent.split(':')[0]
          qc.quoteUser = memberId
          qc.content = chatContent.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, '')
          qc.displayName = this.getMemberName(chat.Content)
        }
      } else {
        if (chat.IsSend) {
          // 引用自己的消息
          qc.displayName = this.currentWechat.WeChatNick
          qc.quoteUser = this.currentWechat.WeChatId
          qc.content = chat.Content
        } else {
          // 引用好友的消息
          qc.displayName = this.currentFriend.FriendNick || this.currentFriend.ShowName
          qc.quoteUser = this.currentFriend.FriendId || this.currentFriend.UserName
          qc.content = chat.Content
        }
      }
      this.$store.commit('conversation/SET_QUOTE_MSG', chat.MsgSvrId || chat.MsgSvrId)
      this.$store.commit('conversation/SET_QUOTE_DETAIL', qc)
    },
    // 踢人
    knickSomeBody(chat) {
      // 先判断该好友是否还在群里
      const memberId = chat.Content.split(':')[0]
      const memberName = this.getMemberName(chat.Content)
      // 如果要踢的人已经不在群聊
      if (this.currentFriend.MemberList.indexOf(memberId) < 0) {
        this.$message.warning('该成员已经不在群里！')
        return
      }
      this.$confirm(`是否确认删除成员 ${memberName} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.knicking = true
          const message = {
            WeChatId: this.currentWeChatId, // string 商家所属微信号
            ChatRoomId: this.currentFriendId, // string 群聊id
            Action: 3, // EnumChatRoomAction 指令
            Content: memberId // string 指令内容
          }
          this.$store.dispatch('websocket/ChatRoomActionTask', message)
          setTimeout(() => {
            this.knicking = false
          }, 2000)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
    // // 鼠标右键
    // rightEvent(event, chat) {
    //   this.showRight = false
    //   this.chatChose = chat
    //   const top = event.pageY
    //   const left = event.pageX
    //   const re = document.getElementById('chatRightEvents')
    //   re.style.top = top + 'px'
    //   re.style.left = left + 'px'
    //   this.showRight = true
    // },
    // // 隐藏右键菜单 废弃
    // hideRight() {
    //   this.showRight = false
    // }
  }
}
</script>

<style lang="scss" scoped>
.big-img-box {
  position: absolute;
  top: 0;
  right: -200px;
}

.show-chats {
  height: 65%;
  overflow-x: hidden;
  overflow-y: scroll;

  ::v-deep .quote-content {
    padding: 2px 5px;
    background-color: #e8e8e8;
  }

  // #chatRightEvents {
  //   position: absolute;
  //   display: flex;
  //   flex-direction: column;
  //   justify-content: center;
  //   align-items: center;
  //   padding: 10px;
  //   width: 150px;
  //   background: #fff;
  //   border: solid #dcdfe6 1px;
  //   .close-btn {
  //     position: absolute;
  //     top: 0;
  //     right: 5px;
  //     font-size: 16px;
  //     cursor: pointer;
  //     &:hover {
  //       color: #41c0fc;
  //     }
  //   }
  // }

  .chat-item {
    display: flex;
    flex-direction: column;
    margin: 5px;

    .chat-time {
      font-size: 12px;
      padding: 5px 10px;
      border-radius: 5px;
      color: white;
      margin: 5px auto;
      background: #dadada;
    }

    .chat-content {
      display: flex;
      position: relative;
      padding-top: 10px;
      font-size: 12px;
      color: $font-color-base;

      .member-info {
        max-width: 60%;
        position: absolute;
        color: $font-color-2;
        top: 0;
        left: 48px;
      }

      .content-content {
        max-width: 60%;
        min-height: 40px;
        line-height: 25px;
        padding: 5px;
        margin-left: 7px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        position: relative;
        background: white;
        word-break: break-all;
        border: 1px solid #e7e7e7;

        ::v-deep .chat-img {
          width: 100px;
          height: auto;
        }

        .chat-text {
          font-size: 14px;
        }

        .chat-picture {
          width: 100px;
          display: flex;
          align-items: center;
        }

        .chat-voice {
          width: 300px;
          max-width: 100%;
          display: flex;
          align-items: center;
        }

        ::v-deep .chat-video {
          display: flex;
          align-items: center;
          position: relative;

          .play-video {
            color: #98e165;
            position: absolute;
            font-size: 50px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            cursor: pointer;
          }

          .video-box {
            width: 200px;
            height: auto;
          }

          .video-box-no {
            width: 100px;
            height: auto;
          }
        }

        ::v-deep .chat-system {
          color: gray;

          a {
            color: #41c0fc;
          }
        }

        ::v-deep .chat-link {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;

          .link-title {
            font-size: 14px;
            font-weight: 600;
          }

          .link-content {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .link-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 10px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }

            .link-img {
              max-width: 50px;
              max-height: 50px;
              min-height: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
          }

          .link-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }

        ::v-deep .chat-file {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;

          .file-title {
            font-size: 14px;
            font-weight: 600;
          }

          .file-content {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .file-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 12px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }

            .file-icon {
              font-size: 30px;
              margin-right: 20px;
            }
          }

          .file-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }

        ::v-deep .chat-app {
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          display: flex;
          flex-direction: column;

          .app-des {
            display: flex;

            .app-icon {
              width: 20px;
              height: 20px;
            }

            .app-source {
              width: 100%;
              font-size: 12px;
              margin-left: 5px;
              color: gray;
            }
          }

          .app-title {
            width: 100%;
            height: 30px;
            font-size: 12px;
            font-weight: 600;
            line-height: 30px;
          }

          .app-img {
            align-self: center;
            max-width: 200px;
          }

          .app-typestr {
            height: 25px;
            margin-top: 5px;
            line-height: 25px;
            color: gray;
            text-align: start;
            border-top: solid #aaaaaa 1px;
          }
        }

        ::v-deep .chat-namecard {
          width: 300px;
          max-width: 100%;
          cursor: pointer;

          .namecard-info {
            display: flex;
            align-items: center;

            .namecard-img {
              height: 50px;
              width: 50px;
              min-width: 50px;
              border-radius: 5px;
            }

            .namecard-nickname {
              width: 250px;
              font-size: 14px;
              margin-left: 5px;
            }
          }

          .namecard-tip {
            color: gray;
            margin-top: 5px;
            border-top: #aaaaaa solid 1px;
          }
        }

        ::v-deep .chat-luckmoney {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;

          .luck-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;

            .luck-img {
              max-width: 50px;
            }

            .wish-open {
              display: flex;
              flex-direction: column;
            }

            .luck-wish {
              width: 200px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .luck-flag {
              width: 60px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .money-opened {
              margin-left: 10px;
              color: white;
            }
          }

          .luckmoney-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }

          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }

        ::v-deep .chat-moneytran {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;

          .moneytran-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;

            .moneytran-img {
              max-width: 30px;
              margin-left: 10px;
            }

            .moneytran-feed,
            .moneytran-flag {
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }
          }

          .moneytran-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }

          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }
      }

      .send-state {
        display: flex;
        align-items: center;
        justify-content: center;
        max-width: 30%;
        flex-wrap: wrap;
      }

      .chat-room {
        margin-top: 20px;
      }

      .triangle {
        &::before {
          content: '';
          border: 6px solid transparent;
          border-right: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          left: -13px;
        }

        &::after {
          content: '';
          border: 6px solid transparent;
          border-right: 6px solid white;
          position: absolute;
          top: 10px;
          left: -12px;
        }

        &:hover {
          background-color: #f6f6f6;

          &::after {
            content: '';
            border: 6px solid transparent;
            border-right: 6px solid #f6f6f6;
            position: absolute;
            top: 10px;
            left: -12px;
          }
        }
      }

      .triangle-send {
        margin-right: 7px;
        background: #9eea6a;

        &::before {
          content: '';
          border: 6px solid transparent;
          border-left: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          right: -13px;
        }

        &::after {
          content: '';
          border: 6px solid transparent;
          border-left: 6px solid #9eea6a;
          position: absolute;
          top: 10px;
          right: -12px;
        }

        &:hover {
          background-color: #98e165;

          &::after {
            border-left: 6px solid #98e165;
          }
        }
      }

      .system-info {
        border: none;
        max-width: 80%;
        margin: 0 auto;
        background: inherit;
      }
    }

    .chat-content-send {
      flex-direction: row-reverse;
    }
  }

  ::v-deep .detail-dialog {
    overflow: hidden;

    .el-dialog {
      overflow: hidden;
      height: 500px;
      min-width: 500px;
      display: flex;
      flex-direction: column;

      .el-dialog__body {
        overflow: hidden;
        margin: auto;
        flex: 1 1 auto;
        display: flex;
        align-items: center;
        justify-content: center;

        .detail-dialog-img {
          @include scroll;
          max-height: 100%;
          max-width: 100%;
          overflow: auto;
        }

        .detail-dialog-video {
          max-height: 100%;
          width: auto;
        }
      }
    }
  }

  .member-detail {
    display: flex;
    flex-direction: column;

    ::v-deep .el-dialog {
      width: 500px;

      .el-dialog__body {
        padding: 20px;
      }
    }

    .member-detail-info {
      display: flex;

      .member-detail-text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20px;
        overflow: hidden;
      }
    }

    .member-detail-btns {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
  }

  ::v-deep .transport-message {
    .el-dialog {
      .el-dialog__body {
        padding: 0;

        .el-tabs {
          padding: 0 10px;

          .friends-list {
            height: 400px;
            overflow: auto;
            display: flex;
            flex-direction: column;
            align-items: center;

            .el-pagination {
              margin: 5px 0;
            }
          }
        }
      }
    }
  }
}
</style>
